package edu.zju.gis.dbfg.fileserver.interceptor;

import java.lang.reflect.Method;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.util.Properties;

import com.github.pagehelper.PageHelper;
import edu.zju.gis.dbfg.fileserver.model.Role;
import edu.zju.gis.dbfg.fileserver.service.RoleService;
import edu.zju.gis.dbfg.fileserver.util.SpringUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.*;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.DefaultReflectorFactory;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.factory.DefaultObjectFactory;
import org.apache.ibatis.reflection.wrapper.DefaultObjectWrapperFactory;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Intercepts(@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}))
public class AuthorityInterceptor implements Interceptor {

    private final String sqlPrefix = "select * from (";
    private final String sqlPostfix = ") as temp where temp.departments like \"%{0}%\" and temp.level <= {1}";

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        UserAuth userAuth = getPermissionByDelegate(mappedStatement);
        if (userAuth == null) {
            return invocation.proceed();
        }
        // 获取request信息，得到当前登录用户信息
        RequestAttributes req = RequestContextHolder.getRequestAttributes();
        if (req == null) {
            return invocation.proceed();
        }

        HttpServletRequest request = ((ServletRequestAttributes) req).getRequest();
        //如果request里面的用户信息为空，则直接抛异常
        if (request.getSession().getAttribute("userId") == null) {
            throw new RuntimeException("用户未登陆！");
        }
        //获取request内的信息
        String userId = request.getSession().getAttribute("userId").toString();
        RoleService roleService = SpringUtil.getBean(RoleService.class);
        Role role = roleService.departmentsAndLevel(userId);
        String userDepartment = role.getDepart();
        int userLevel = role.getUsrlevel();
        // 获取sql
        String sql = getSqlByInvocation(invocation);
        if (StringUtils.isBlank(sql)) {
            return invocation.proceed();
        }

        String sql2Reset = MessageFormat.format(sqlPrefix + sql + sqlPostfix, userDepartment, Integer.toString(userLevel));

        // 包装sql后，重置到invocation中
        resetSql2Invocation(invocation, sql2Reset);
        //如果插叙结果需要分页，需要再次设置PageHelper
        if (userAuth.ifPagination()) {
            String pageNo = request.getParameter("pageNo");
            String pageSize = request.getParameter("pageSize");
            PageHelper.startPage(pageNo != null ? Integer.parseInt(pageNo) : 1, pageSize != null ? Integer.parseInt(pageSize) : 20);
        }
        // 返回，继续执行
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object obj) {
        return Plugin.wrap(obj, this);
    }

    @Override
    public void setProperties(Properties prop) {
        System.out.println("setPro");
        // doSomething
    }

    /**
     * 获取sql语句
     *
     * @param invocation
     * @return
     */
    private String getSqlByInvocation(Invocation invocation) {
        final Object[] args = invocation.getArgs();
        MappedStatement ms = (MappedStatement) args[0];
        Object parameterObject = args[1];
        BoundSql boundSql2 = ms.getBoundSql(parameterObject);
        return boundSql2.getSql();
    }

    /**
     * 包装sql后，重置到invocation中
     *
     * @param invocation
     * @param sql
     * @throws SQLException
     */
    private void resetSql2Invocation(Invocation invocation, String sql) throws SQLException {
        final Object[] args = invocation.getArgs();
        MappedStatement statement = (MappedStatement) args[0];
        Object parameterObject = args[1];
        BoundSql boundSql = statement.getBoundSql(parameterObject);
        MappedStatement newStatement = newMappedStatement(statement, new BoundSqlSqlSource(boundSql));
        MetaObject msObject = MetaObject.forObject(newStatement, new DefaultObjectFactory(), new DefaultObjectWrapperFactory(), new DefaultReflectorFactory());
        msObject.setValue("sqlSource.boundSql.sql", sql);
        args[0] = newStatement;
    }

    private MappedStatement newMappedStatement(MappedStatement ms, SqlSource newSqlSource) {
        MappedStatement.Builder builder =
                new MappedStatement.Builder(ms.getConfiguration(), ms.getId(), newSqlSource, ms.getSqlCommandType());
        builder.resource(ms.getResource());
        builder.fetchSize(ms.getFetchSize());
        builder.statementType(ms.getStatementType());
        builder.keyGenerator(ms.getKeyGenerator());
        if (ms.getKeyProperties() != null && ms.getKeyProperties().length != 0) {
            StringBuilder keyProperties = new StringBuilder();
            for (String keyProperty : ms.getKeyProperties()) {
                keyProperties.append(keyProperty).append(",");
            }
            keyProperties.delete(keyProperties.length() - 1, keyProperties.length());
            builder.keyProperty(keyProperties.toString());
        }
        builder.timeout(ms.getTimeout());
        builder.parameterMap(ms.getParameterMap());
        builder.resultMaps(ms.getResultMaps());
        builder.resultSetType(ms.getResultSetType());
        builder.cache(ms.getCache());
        builder.flushCacheRequired(ms.isFlushCacheRequired());
        builder.useCache(ms.isUseCache());

        return builder.build();
    }

    //    定义一个内部辅助类，作用是包装sq
    class BoundSqlSqlSource implements SqlSource {
        private BoundSql boundSql;

        public BoundSqlSqlSource(BoundSql boundSql) {
            this.boundSql = boundSql;
        }

        @Override
        public BoundSql getBoundSql(Object parameterObject) {
            return boundSql;
        }
    }

    private UserAuth getPermissionByDelegate(MappedStatement mappedStatement) {
        UserAuth dataAuth = null;
        try {
            String id = mappedStatement.getId();
            String className = id.substring(0, id.lastIndexOf("."));
            String methodName = id.substring(id.lastIndexOf(".") + 1, id.length());
            final Class<?> cls = Class.forName(className);
            final Method[] method = cls.getMethods();
            for (Method me : method) {
                if (me.getName().equals(methodName) && me.isAnnotationPresent(UserAuth.class)) {
                    dataAuth = me.getAnnotation(UserAuth.class);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dataAuth;
    }
}
